package sg.edu.nus.iss.billing.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import sg.edu.nus.iss.billing.common.exception.BadDbCallException;

/**
 * @author Chee Ann
 *
 */
public class DbUtil {
	
	public final static String DELIMITER = "^";
	public static String  logClass = "CLASSNAME DbUtil : ";
	
	public static List<String> loadDb(String dbPath) throws BadDbCallException {
		ArrayList<String> data = new ArrayList<String>();
		File f = new File(dbPath);
		FileInputStream fs = null;
        InputStreamReader in = null;
        BufferedReader br = null;
        String textinLine = null;
        String logClass1  = logClass+" loadDb() FILE "+dbPath;
        printLog(logClass1);
        
        try {
        	if(!f.exists())
        			f.createNewFile();
        	fs = new FileInputStream(f);
            in = new InputStreamReader(fs);
            br = new BufferedReader(in);
            
            
            
            while(true)
            {
                textinLine=br.readLine();
                printLog(logClass1 + " "+textinLine );
                if(textinLine==null)
                    break;
                data.add(textinLine.trim());
                
            }
            fs.close();
            in.close();
            br.close();
            
        } catch (FileNotFoundException e) {
        	throw new BadDbCallException("File Not Found: " + dbPath + ". " + e.getMessage());
        } catch (IOException e) {
        	throw new BadDbCallException("Unable to load from db: " + dbPath + ". " + e.getMessage());
        }
		return data;
	}
	
	public static void printDb(List<String> data){
		for (int i=0;i<data.size();i++ ){
			System.out.println(data.get(i));
		}
	}
	
	public static void saveDb(String dbPath, List<String> data) throws BadDbCallException {
		File f = new File(dbPath);
        FileWriter fstream;
		try {
			fstream = new FileWriter(f);
	        BufferedWriter outobj = new BufferedWriter(fstream);
	        for (int i=0;i<data.size();i++){
	            outobj.write(data.get(i));
	            outobj.newLine();
	        }
	        outobj.close();
		} catch (IOException e) {
			throw new BadDbCallException("Unable to save to db. Path:" + dbPath + ". " + e.getMessage());
		}
	}
	
	private static void printLog(String str){
		System.out.println(str);
	}
}
